package com.gt.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gt.task.RestTemplateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.List;

/**
 * RestTemplate拦截器，进行日志打印
 */
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    private List<RestTemplateTask> taskList;
    public LoggingRequestInterceptor(){}

    public LoggingRequestInterceptor(List<RestTemplateTask> taskList){
        this.taskList = taskList;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        long start = System.currentTimeMillis();
        ClientHttpResponse response = execution.execute(request, body);
        long end = System.currentTimeMillis();

        if (taskList!=null&&taskList.size()>0){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("timeConsuming",end-start);//耗时
            for (RestTemplateTask task : taskList) {
                task.execute(request,response,body,jsonObject);
            }
        }
        return response;
    }


}